import * as mongoose from 'mongoose';
import { AccountSchema, Account } from './schema/AccountSchema';
import { DBManager } from './manager/DBManager';
import { Operater } from './Operater';

/**连接数据库 */
export class Connect
{
    private acc_database:mongoose.Connection;
    private games_database:mongoose.Connection;

    constructor()
    {
    }
    /**
     * url:数据库地址
     * type:库类型-->account or games
     */
    public connectByUrl(url:string,type:string):void
    {
        console.log(url);
        let db = mongoose.createConnection('mongodb://' + url);
        let self = this;
        db.on('error',console.error.bind(console,'connection error:'));
        db.once('open',function(){
            console.log(url,'connected...');
            switch(type)
            {
                case "account":
                    self.acc_database = db;
                    break;
                case "games":
                    self.games_database = db;
                    break;
            }
            self.checkComplete();
        });
    }

    private checkComplete():void
    {
        if(this.acc_database && this.games_database)
        {
            //数据库访问测试
            // this.acc_database
            this.initCollections();
            DBManager.getInstance();
            // this.test();
        }
    }

    /**初始化需要操作的表 */
    private initCollections():void
    {
        let schema = new AccountSchema();
        Operater.AccountEntity = this.acc_database.model('account',schema,'base');
    }

    private test():void
    {
        Operater.queryByFactor(Operater.AccountEntity,{}).then(function(result){
            console.log(result);
        });

        Operater.addDoc(Operater.AccountEntity,{});
    }
}